package com.feng.financial.common.exception;

import com.feng.financial.common.web.WebCommonResponse;
import com.feng.financial.common.web.WebCommonResponseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;

/**
 * @author Lee
 * 全局异常处理
 */
@RestControllerAdvice
public class WebExceptionHandle {

    private final  static Logger LOGGER = LoggerFactory.getLogger(WebExceptionHandle.class);

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public WebCommonResponse<Void> hibernateValidationHandler(MethodArgumentNotValidException e){
        StringBuilder desc = new StringBuilder("请求参数错误：" + e.getMessage());
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if (allErrors != null && allErrors.size() != 0) {
            desc = new StringBuilder("请求参数错误：");
            for (ObjectError allError : allErrors) {
                MethodArgumentNotValidVo methodArgumentNotValidVo = new MethodArgumentNotValidVo(allError.getObjectName(), allError.getDefaultMessage(), Arrays.toString(allError.getCodes()));
                        desc.append(methodArgumentNotValidVo.toString());
            }
        }
        LOGGER.info(desc.toString());
        return new WebCommonResponseBuilder<Void>().fail(ErrorCode.PARAM_ERROR.getStatusCode(), desc.toString()).build();
    }

    @ExceptionHandler({Exception.class})
    public WebCommonResponse<Void> customerExceptionHandler(Exception e){
        e.printStackTrace();
        String desc = e.getMessage();
        LOGGER.info(desc);
        return new WebCommonResponseBuilder<Void>().fail(ErrorCode.SYSTEM_ERROR.getStatusCode(), desc).build();
    }

}
